package com.gs.disk.modules.headImgAndWallper.controller.admin;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.gs.entity.GeneralPage;
import com.gs.entity.R;
import com.gs.common.util.DateTimeUtil;
import com.gs.disk.controller.common.OssController;
import com.gs.disk.entity.OssEntity;
import com.gs.disk.modules.headImgAndWallper.dao.admin.AdminResourceDao;
import com.gs.disk.modules.headImgAndWallper.dto.ResourceDto;
import com.gs.disk.modules.headImgAndWallper.entity.CategoryEntity;
import com.gs.disk.modules.headImgAndWallper.entity.ResourceEntity;
import com.gs.disk.modules.headImgAndWallper.service.admin.AdminCategoryService;
import com.gs.disk.modules.headImgAndWallper.service.admin.AdminResourceService;
import com.gs.disk.service.common.MinioService;
import com.gs.disk.service.common.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

@RestController
@RequestMapping("disk/admin/resource")
@Api(tags = "后台壁纸头像管理")
@ApiSort(4)
public class AdminResourceController extends ServiceImpl<AdminResourceDao, ResourceEntity> {

    @Resource
    private AdminResourceService service;

    @Resource
    private AdminResourceDao dao;

    @Resource
    private OssController ossController;

    @Resource
    private OssService ossService;

    @Resource
    private MinioService minioService;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Resource
    private AdminCategoryService categoryService;

    @GetMapping("")
    @ApiOperation("资源列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "分类名", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "总页数", paramType = "query")
    })
//    @Cacheable(value = "adminResourceList", keyGenerator = "myKeyGenerator")
    public R<GeneralPage<ResourceDto>> list(@ApiIgnore @RequestParam Map<String, Object> params) {
        GeneralPage<ResourceDto> list = service.list(params);
        return R.ok(list);
    }

    @PutMapping("save")
    @ApiOperation("保存资源")
    public R saveResource(@RequestBody ResourceEntity entity) {
        // categoryName
        Long categoryId = entity.getCategoryId();

        CategoryEntity categoryEntity = categoryService.get(categoryId);

        entity.setCategoryName(categoryEntity.getCategoryName());
        // ossInfo
        OssEntity ossEntity = ossService.get(entity.getOssFileId());
        entity.setOldFileName(ossEntity.getOssFileName());

        // 获取最大排序
        Integer maxSort = service.getMaxSort();
        entity.setSort(maxSort);

        // 正常不会为null, 若为null, 说明全部为null(后加字段)
        if(ObjectUtil.isNull(maxSort)) {
            List<ResourceEntity> resourceEntities = dao.selectList(null);

            AtomicReference<Integer> currentSort = new AtomicReference<>(1);

            resourceEntities.forEach(r -> {
                r.setSort(currentSort.getAndSet(currentSort.get() + 1));
            });

            updateBatchById(resourceEntities);

        }

        service.upsert(entity);
        return R.ok();
    }

    @PutMapping("batchSave")
    @Transactional
    @ApiOperation("批量保存资源")
    public R save(@RequestParam Long categoryId, @RequestParam("file") MultipartFile[] files) {
        // categoryName
        CategoryEntity categoryEntity = categoryService.get(categoryId);
        String categoryName = categoryEntity.getCategoryName();
        String path = "/wallper/" + DateTimeUtil.currentTimeUTf8();

        List<ResourceEntity> resourceList = new LinkedList();
        for (MultipartFile file : files) {
            ResourceEntity resourceEntity = new ResourceEntity();
            resourceEntity.setCategoryId(categoryId);
            resourceEntity.setCategoryName(categoryName);
            Long ossFileId = Convert.toLong(ossController.upload(file, bucketName, path).getData());

            OssEntity ossEntity = ossService.get(ossFileId);
            // ossInfo
            resourceEntity.setOldFileName(ossEntity.getOssFileName());
            resourceEntity.setOssFileId(ossFileId);
            resourceList.add(resourceEntity);
        }


        service.batchSave(resourceList);
        return R.ok();
    }




    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除资源")
    public R delete(@PathVariable Long id) {
        service.delete(id);
        return R.ok();
    }


    @GetMapping("generateThumbnailFile")
    @ApiOperation("生成图片缩略图")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "分类名", paramType = "query"),
            @ApiImplicitParam(name = "scale", value = "分类名", paramType = "query"),
    })
    @Transactional
//    @CacheEvict("adminResourceList")
    public R generateThumbnailFile(
            @RequestParam(required = false) Long categoryId,
                                   @RequestParam(required = false, defaultValue = "0.2") String scale) throws Exception {
        service.generateThumbnailFile(categoryId, scale);
        return R.ok();
    }

}
